<template>
  <el-card class="chart-card">
    <h3 class="chart-title">热门活动投票 TOP5</h3>
    <div class="chart-container">
      <canvas ref="barChartRef"></canvas>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Chart, registerables } from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { getHotVoteTop5 } from '@/api/business/dashboard';


Chart.register(...registerables, ChartDataLabels);
const barChartRef = ref(null);
let chartInstance = null;

// 获取数据并绘制图表
onMounted(async () => {
  const res = await getHotVoteTop5();
  const data = res.data;
  const labels = data.map(item => item.voteTitle);
  const votes = data.map(item => item.votes);

  // 蓝色渐变
  const ctx = barChartRef.value.getContext('2d');
  const blueGradient = ctx.createLinearGradient(0, 0, 0, 300);
  blueGradient.addColorStop(0, 'rgba(22, 93, 255, 0.8)');
  blueGradient.addColorStop(1, 'rgba(22, 93, 255, 0.4)');

  chartInstance = new Chart(barChartRef.value, {
    type: 'bar',
    data: {
      labels,
      datasets: [{
        label: '票数',
        data: votes,
        backgroundColor: blueGradient,
        borderRadius: 4,
        barThickness: 30
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        x: { grid: { display: false } },
        y: { beginAtZero: true, grid: { color: 'rgba(0,0,0,0.05)' } }
      },
      plugins: {
        datalabels: {
          anchor: 'end',
          align: 'top',
          color: '#333',
          formatter: (v) => new Intl.NumberFormat().format(v)
        }
      }
    }
  });
});
</script>

<style scoped>
.chart-card { height: 300px; padding: 15px; }
.chart-title { font-size: 16px; color: #333; margin-bottom: 10px; }
.chart-container { width: 100%; height: 200px; }
</style>